package td.pt.other;

import td.domain.Category;

import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.cell.client.Cell;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.SingleSelectionModel;
import com.google.gwt.view.client.TreeViewModel;

/**
 * The model that defines the nodes in the tree.
 */
public class CategoryTreeModel implements TreeViewModel {

	SingleSelectionModel<Category> selectionModel;
	private ListDataProvider<Category> rootDataProvider;

	public CategoryTreeModel(SingleSelectionModel<Category> selectionModel) {
		this.selectionModel = selectionModel;
	}

	/**
	 * Get the {@link NodeInfo} that provides the children of the specified
	 * value.
	 */
	public <T> NodeInfo<?> getNodeInfo(T value) {
		// Root level
		if (value instanceof Category) {
			Category category = (Category) value;
			if (category.getChildren() == null) {
				return null;
			}
			ListDataProvider<Category> dataProvider = new ListDataProvider<Category>(
					category.getChildren());

			if (category.getParent() == null) {
				this.rootDataProvider = dataProvider;
			}

			return new DefaultNodeInfo<Category>(dataProvider, cell,
					selectionModel, null);
		}
		return null;
	}

	public void refresh() {
		this.rootDataProvider.refresh();
	}

	/**
	 * Check if the specified value represents a leaf node. Leaf nodes cannot be
	 * opened.
	 */
	public boolean isLeaf(Object value) {
		if (value instanceof Category) {
			Category category = (Category) value;
			return category.getChildren() == null;
		}
		return true;
	} // Create a cell to display a composer.

	Cell<Category> cell = new AbstractCell<Category>() {
		@Override
		public void render(Context context, Category category,
				SafeHtmlBuilder sb) {
			if (category != null) {
				sb.appendHtmlConstant("<b>")
						.appendEscaped(category.getName())
						.appendHtmlConstant("</b><br/>")
						.appendEscaped(
								"Thoughts: " + category.getNumThoughts()
										+ ", Reads: " + category.getNumReads());
			}
		}
	};
}
